import { withRouter } from 'next/router';
import Link from 'next/link';
import React, { useState, useEffect } from 'react';
import { message } from 'antd';
import Cookies from 'js-cookie';
// api
import { hotSearchProduct } from '@/api/search';

const Search = ({ router }) => {

    const [keywords, setKeywords] = useState('');
    const [hotList, setHotList] = useState([]);

    // 热门搜索商品展示
    useEffect(() => {
        hotSearchProduct().then(res => {
            const { code, data } = res;
            if(code === 0 && data && data.length) {
                setHotList([...data]);
            }
        })
    }, []);

    // 开启搜索
    function openSearch(keywords) {
        if (!keywords.trim()) {
            message.warning('请输入搜索关键字');
            return false
        }
        Cookies.set('keywords', keywords);
        router.push(`/search?word=${keywords}`);
    }

    return (
        <div className="search-box">
            <div className="search">
                <span className="iconfont icon-sousuo"></span>
                <input
                    type="text"
                    placeholder="门票/酒店/线路/用车等"
                    value={keywords}
                    onChange={(e) => setKeywords(e.target.value)}
                    onKeyUp={(e) => {
                        if (e.key === "Enter") {
                            openSearch(e.target.value)
                        }
                    }}
                />
                <div className="btn" onClick={() => { openSearch(keywords) }}>搜 索</div>
            </div>
            {
                hotList.length ?
                <div className="search-hot">
                    热门搜索：
                    {
                        hotList.map((item, index) => {
                            return (
                                <Link href={`/search?word=${item}&from=keyword`} key={index} prefetch={false}>
                                    <a target="_blank">{item}</a>
                                </Link>
                            )
                        })
                    }
                </div> : ""
            }
        </div>
    )
}

export default withRouter(Search)